package api

import (
	"api/app/{{ table.path }}/documents"
	"api/config/code"
	"api/libs/api"
	"api/libs/morm"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
	"go.mongodb.org/mongo-driver/bson/primitive"
)
type {{ table.name }}Api struct {
api.BaseApi
}
func (c *{{ table.name }}Api) Prepare() {
c.RoutePrefix = fmt.Sprintf("/{{ table.path }}/admin/%s", "{{ table.name }}")
// 必要步骤
c.SetBefore(func(operation *server.Operation) {
//执行此方法前operation 已经赋值到BaseApi.Operation
})
}



func (c *{{ table.name }}Api) SaveAction(operation *server.Operation) {
this := c.TakeOver(operation)
factory := morm.NewFactory()
model := new(documents.{{ table.name }})
if this.Try(this.FillJson(model)) {
return
}
factory.TriggerNew(model)
if model.Id.IsZero() {
if this.Try(factory.Create(model)) {
return
}
} else {
if this.Try(factory.Update(model)) {
return
}
}
this.ReturnSuccess("保存成功", model)
}

func (c *{{ table.name }}Api) GetAction(operation *server.Operation) {
this := c.TakeOver(operation)
factory := morm.NewFactory()
model := new(documents.{{ table.name }})
id := this.Get(`id`).IsString()
if this.Try(factory.Find(model, id)) {
return
}
this.ReturnSuccess("OK", model)
}

func (c *{{ table.name }}Api) ListAction(operation *server.Operation) {
this := c.TakeOver(operation).GetHttpQuery()
factory := morm.NewFactory()
list := make([]*documents.{{ table.name }}, 0)
factory.SetDoc(&documents.{{ table.name }}{})
e := factory.FindBy(&list, this.HttpQuery)
if this.Try(e) {
return
}
count, e := factory.Count(this.HttpQuery)
if this.Try(e) {
return
}
outPut := server.NewJsonOut(code.Success, "列表获取成功", ez.M{
"lists": list,
"query": ez.M{"page": this.HttpQuery.Page, "limit": this.HttpQuery.Limit, "total": count},
})
this.JsonOut(outPut)
}

func (c *{{ table.name }}Api) DeleteAction(operation *server.Operation) {
this := c.TakeOver(operation)
factory := morm.NewFactory()
id := operation.Get(`id`).IsString()
oid, e := primitive.ObjectIDFromHex(id)
if this.Try(e) {
return
}
if this.Try(factory.Delete(&documents.{{ table.name }}{Id: oid})) {
return
}
this.ReturnSuccess("删除成功", "")
}
